package com.horse.three60;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.fb.android.FacebookShareManager;
import com.horse.share.twitter.TwitterShareManager;
import com.horse.utils.Constants;
import com.horse.utils.Downloader;
import com.horse.utils.NoRepeatRandom;
import com.horse.utils.Utils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class RecallQuizeActivity extends Activity implements OnClickListener {

	private TextView timerView;
	private TextView tView;
	private TextView scoreView;
	private ImageView pauseView;
	private ImageView imageView;

	private Button mainMenuButton;
	private Button tryButton;
	private Button twitterButton;
	private Button facebookButton;
	private ImageView pinView;
	private Bitmap bitmap;

	private Button quizeButton;
	private Button exitButton;
	private Button resumeButton;

	private boolean isTimer;

	private NoRepeatRandom nrr;

	private int randomValue;

	private int currentPosition = -1;
	private int score = 0;

	private TextView quesTextView;
	private boolean isClick;
	private boolean isExit;
	private boolean isNextQuestion = true;

	private TextView alertView;
	private TextView congratulationView;
	private TextView miliView;

	private int targetPosition[];

	private RelativeLayout recallLayout;

	private List<JSONArray> items;

	private String jsonString;
	private int level;
	private String partFileName;

	private boolean isFirstTime = true;
	private boolean isPinDrop;

	private RelativeLayout imageViewContainer;
	private int imageViewWidth;
	private int imageViewHeight;
	private float factor;

	private boolean isNextLevel;

	private int bonusScore;
	private CountDownTimer timer;

	private long pauseBefore;
	private long pauseAfter;
	private long pauseTime = 0;
	private boolean isPause;

	private File files[];

	private ImplementQuiz iquize;
	private int quizeIndex;
	private long remainingTime;
	private int correctAnswer = 0;
	private int length;
	private int numOfQuestion;

	private JSONArray ja;
	private JSONObject jo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.layout_recall);
			bitmap = BitmapFactory.decodeResource(getResources(),
					R.drawable.pin_drop);
			recallLayout = (RelativeLayout) findViewById(R.id.recallLayout);

			items = new ArrayList<JSONArray>();

			dropPin();

			imageViewContainer = (RelativeLayout) findViewById(R.id.image_view_container);
			alertView = (TextView) findViewById(R.id.alertView);
			congratulationView = (TextView) findViewById(R.id.congratulationView);
			imageView = (ImageView) findViewById(R.id.imageView);
			timerView = (TextView) findViewById(R.id.timerView);
			tView = (TextView) findViewById(R.id.tView);
			scoreView = (TextView) findViewById(R.id.scoreView);
			quesTextView = (TextView) findViewById(R.id.questionNumberView);

			pauseView = (ImageView) findViewById(R.id.pauseView);
			pauseView.setOnClickListener(this);

			quizeButton = (Button) findViewById(R.id.quizeButton);

			exitButton = (Button) findViewById(R.id.exitButton);
			exitButton.setOnClickListener(this);

			resumeButton = (Button) findViewById(R.id.resumeButton);
			resumeButton.setOnClickListener(this);

			mainMenuButton = (Button) findViewById(R.id.mainMenuButton);
			mainMenuButton.setOnClickListener(this);

			tryButton = (Button) findViewById(R.id.tryButton);
			tryButton.setOnClickListener(this);

			twitterButton = (Button) findViewById(R.id.twitterButton);
			twitterButton.setOnClickListener(this);

			facebookButton = (Button) findViewById(R.id.facebookButton);
			facebookButton.setOnClickListener(this);

			imageView.setOnTouchListener(new View.OnTouchListener() {
				@Override
				public boolean onTouch(View arg0, MotionEvent event) {
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						if (isClick) {
							if (isTimer) {
								timer.cancel();
							}
							posX = (int) event.getX();
							posY = (int) event.getY();
							// widthFactor = Utils.getWidthDpiFactor(this);
							// heightFactor = Utils.getHeightDpiFactor(this);
							implementQuiz();

						}
						break;
					}
					return false;
				}
			});

			imageViewContainer.post(new Runnable() {

				@Override
				public void run() {
					try {
						factor = Math.min(
								imageViewContainer.getWidth() / 480.0f,
								imageViewContainer.getHeight() / 320.0f);
						recallLayout.getLayoutParams().width = imageView
								.getLayoutParams().width = imageViewWidth = (int) (480 * factor);
						recallLayout.getLayoutParams().height = imageView
								.getLayoutParams().height = imageViewHeight = (int) (320 * factor);
						playQuize();
					} catch (Exception e) {
						e.printStackTrace();
						Utils.showAlertMessage(RecallQuizeActivity.this, null,
								e.getMessage());
					}
				}
			});

			isTimer = getIntent()
					.getBooleanExtra(Constants.KEY_IS_TIMER, false);
			if (!isTimer) {
				timerView.setVisibility(View.GONE);
				findViewById(R.id.tView).setVisibility(View.GONE);
			}
			jsonString = getIntent().getStringExtra(Constants.KEY_JSON_STRING);

			level = getIntent().getIntExtra(Constants.KEY_LEVEL, 0);
			Log.i("DREG", "Level=" + level);

			getJsonData(level);
			getPointsList();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private void playQuize() {
		getJsonData(level);
		// showQuizeAimation();
		iquize = new ImplementQuiz(currentPosition, Constants.WAITING_TIME);
		iquize.execute();
	}

	private void getJsonData(int level) {
		String jsonFileName;
		try {

			switch (level) {
			case 0:
				jsonFileName = "Level 1-Quiz 2 Answers.json";
				break;
			case 1:
				jsonFileName = "Level 2-Quiz 2 Answers.json";
				break;
			case 2:
				jsonFileName = "Level 3-Quiz 2 Answers.json";
				break;
			case 3:
				jsonFileName = "Level 4-Quiz 2 Answers.json";
				break;

			case 4:
				jsonFileName = "Level 5-Quiz 2 Answers.json";
				break;
			case 5:
				jsonFileName = "Level Hoof 1-Quiz 2 Answers.json";
				break;
			case 6:
				jsonFileName = "Level Hoof 2-Quiz 2 Answers.json";
				break;
			case 7:
				jsonFileName = "Level Hoof 3-Quiz 2 Answers.json";
				break;
			case 8:
				jsonFileName = "Level Hoof 4-Quiz 2 Answers.json";
				break;
			case 9:
				jsonFileName = "Level Tendon 1-Quiz 2 Answers.json";
				break;
			case 10:
				jsonFileName = "Level Tendon 2-Quiz 2 Answers.json";
				break;
			case 11:
				jsonFileName = "Level Joints 1-Quiz 2 Answers.json";
				break;
			case 12:
				jsonFileName = "Level Ligaments 1-Quiz 2 Answers.json";
				break;
			case 13:
				jsonFileName = "Level Head Muscle 1-Quiz 2 Answers.json";
				break;
			case 14:
				jsonFileName = "Level Head Bone 1-Quiz 2 Answers.json";
				break;
			case 15:
				jsonFileName = "Level Teeth 1-Quiz 2 Answers.json";
				break;
			case 16:
				jsonFileName = "Level Organs 1-Quiz 2 Answers.json";
				break;
			case 17:
				jsonFileName = "Level Organs 2-Quiz 2 Answers.json";
				break;
			case 18:
				jsonFileName = "Level Conformation 1-Quiz 2 Answers.json";
				break;
			case 19:
				jsonFileName = "Level Conformation 2-Quiz 2 Answers.json";
				break;
			case 20:
				jsonFileName = "Level 6-Quiz 2 Answers.json";
				break;
			default:
				jsonFileName = "Level 1-Quiz 2 Answers.json";
				break;
			}

			jo = new JSONObject(new String(
					Utils.getFileData(this, jsonFileName)));

			ja = jo.getJSONObject("root").getJSONArray("horse");
			numOfQuestion = ja.length();
			for (int k = 0; k < ja.length(); k++) {
				String fileName = ja.getJSONObject(k).getString("-parent");
				Log.i("DREG", "fileName = " + Utils.getFileName(fileName));
			}

			nrr = new NoRepeatRandom(0, ja.length() - 1);
			targetPosition = new int[ja.length()];

			for (int i = 0; i < ja.length(); i++) {
				targetPosition[i] = nrr.GetRandom();
			}

			Log.i("DREG", "jsonString=" + jo.toString());
			jsonString = jo.toString();

		} catch (JSONException e) {
			e.printStackTrace();

		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			isExit = true;
			imageView.setAlpha(0xFF);
			alertView.setVisibility(View.GONE);
			Intent backIntent = new Intent(RecallQuizeActivity.this,
					RecallBeforeActivity.class);
			backIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(backIntent);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.facebookButton:
			faceBookSharing("I have just scored " + score + " in Horse 360");
			break;
		case R.id.twitterButton:
			shareInTwitter();
			break;
		case R.id.mainMenuButton:
			isExit = true;
			imageView.setAlpha(0xFF);
			Intent intent = new Intent(RecallQuizeActivity.this,
					RecallBeforeActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			break;
		case R.id.tryButton:
			currentPosition = -1;
			isExit = false;
			isNextQuestion = true;
			score = 0;
			scoreView.setText("" + score);
			imageView.setAlpha(0xFF);
			alertView.setVisibility(View.GONE);
			quizeButton.setVisibility(View.VISIBLE);
			quesTextView.setVisibility(View.VISIBLE);
			mainMenuButton.setVisibility(View.INVISIBLE);
			twitterButton.setVisibility(View.INVISIBLE);
			facebookButton.setVisibility(View.INVISIBLE);
			tryButton.setVisibility(View.INVISIBLE);
			if (!isNextLevel) {
				Intent in = new Intent(RecallQuizeActivity.this,
						RecallQuizeActivity.class);
				in.putExtra(Constants.KEY_IS_TIMER, isTimer);
				in.putExtra(Constants.KEY_LEVEL, level);
				startActivity(in);
				// implementQuize();
			} else {
				if ((level < 2) || (level == 19)) {
					++level;
					Intent inten = new Intent(RecallQuizeActivity.this,
							RecallQuizeActivity.class);
					Log.i("DREG", "is Normal=" + isTimer);
					inten.putExtra(Constants.KEY_IS_TIMER, isTimer);
					inten.putExtra(Constants.KEY_LEVEL, level);
					startActivity(inten);
				} else {
					++level;
					try {
						files = Downloader
								.getFileList(getImageDirectory(level));
						if (files != null) {
							Intent i = new Intent(RecallQuizeActivity.this,
									RecallQuizeActivity.class);
							i.putExtra(Constants.KEY_IS_TIMER, isTimer);
							i.putExtra(Constants.KEY_LEVEL, level);
							i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(i);
						} else {
							Intent backIntent = new Intent(
									RecallQuizeActivity.this,
									RecallBeforeActivity.class);
							backIntent
									.putExtra(Constants.KEY_NEXT_LEVEL, level);
							backIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(backIntent);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}

			break;
		case R.id.exitButton:
			isExit = true;
			imageView.setAlpha(0xFF);
			alertView.setVisibility(View.GONE);
			Intent backIntent = new Intent(RecallQuizeActivity.this,
					RecallBeforeActivity.class);
			backIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(backIntent);
			break;
		case R.id.resumeButton:
			isPause = false;
			isNextQuestion = true;
			// if (isTimer) {
			// showTimer(remainingTime);
			// }
			// iquize = new ImplementQuiz(quizeIndex, remainingTime);
			// iquize.execute();
			iquize = new ImplementQuiz(quizeIndex, remainingTime);
			iquize.execute();

			imageView.setAlpha(0xFF);
			// isPause = true;
			imageView.setVisibility(View.VISIBLE);
			quizeButton.setVisibility(View.VISIBLE);
			exitButton.setVisibility(View.GONE);
			resumeButton.setVisibility(View.GONE);
			break;
		case R.id.pauseView:
			// if (isTimer) {
			// timer.cancel();
			// }
			// iquize.cancel(true);
			isPause = true;
			if (isTimer) {
				timer.cancel();
			}
			iquize.cancel(true);

			imageView.setAlpha(0x7F);
			quizeButton.setVisibility(View.GONE);
			exitButton.setVisibility(View.VISIBLE);
			resumeButton.setVisibility(View.VISIBLE);
			break;

		default:
			break;

		}

	}

	private void showTimer(long wait) {
		// timerView.setText("10.0");
		bonusScore = 0;
		timer = new CountDownTimer(wait, 100) {

			@Override
			public void onTick(long millisUntilFinished) {
				String time = "";
				if (isClick) {
					bonusScore = (int) Math
							.ceil((double) millisUntilFinished / 1000);
				}
				remainingTime = millisUntilFinished;

				long second = millisUntilFinished / 1000;
				long tenth = (millisUntilFinished % 1000) / 100;
				time = second + "." + tenth;
				timerView.setText(time);
			}

			@Override
			public void onFinish() {
				timerView.setText(0 + "." + 0);

			}
		}.start();

	}

	private void faceBookSharing(String message) {
		FacebookShareManager fsm = new FacebookShareManager(this, this,
				Constants.FACEBOOK_APP_ID, Constants.FACEBOOK_PERMISSION);
		fsm.shareMessage(message);

	}

	private void shareInTwitter() {
		TwitterShareManager tsm = new TwitterShareManager(
				RecallQuizeActivity.this, this);
		tsm.shareTweet("I have just score " + score + " in Horse 360");
	}

	private String getImageDirectory(int level) {
		String IMAGE_DIRECTORY = "";
		switch (level) {
		case 3:
			IMAGE_DIRECTORY = Constants.MUSLES_DIRECTORY;
			break;

		case 4:
			IMAGE_DIRECTORY = Constants.MUSLES_DIRECTORY;
			break;
		case 5:
			IMAGE_DIRECTORY = Constants.HOOFS_DIRECTORY;
			break;
		case 6:
			IMAGE_DIRECTORY = Constants.HOOFS_DIRECTORY;
			break;
		case 7:
			IMAGE_DIRECTORY = Constants.HOOFS_DIRECTORY;
			break;
		case 8:
			IMAGE_DIRECTORY = Constants.HOOFS_DIRECTORY;
			break;
		case 9:
			IMAGE_DIRECTORY = Constants.DEEP_MUSCLES_DIRECTORY;
			break;
		case 10:
			IMAGE_DIRECTORY = Constants.DEEP_MUSCLES_DIRECTORY;
			break;
		case 11:
			IMAGE_DIRECTORY = Constants.DEEP_MUSCLES_DIRECTORY;
			break;
		case 12:
			IMAGE_DIRECTORY = Constants.DEEP_MUSCLES_DIRECTORY;
			break;
		case 13:
			IMAGE_DIRECTORY = Constants.HEAD_DIRECTORY;
			break;
		case 14:
			IMAGE_DIRECTORY = Constants.HEAD_DIRECTORY;
			break;
		case 15:
			IMAGE_DIRECTORY = Constants.HEAD_DIRECTORY;
			break;
		case 16:
			IMAGE_DIRECTORY = Constants.ORGANS_DIRECTORY;
			break;
		case 17:
			IMAGE_DIRECTORY = Constants.ORGANS_DIRECTORY;
			break;
		case 18:
			IMAGE_DIRECTORY = Constants.ORGANS_DIRECTORY;
			break;
		case 19:
			IMAGE_DIRECTORY = Constants.ORGANS_DIRECTORY;
			break;
		}

		return IMAGE_DIRECTORY;
	}

	private String getFilePath(String fileName) {
		boolean isFound = false;
		fileName = fileName + ".png";
		String path = "";

		if (!isFound) {
			File muscleFile[] = Downloader
					.getFileList(Constants.MUSLES_DIRECTORY);
			if (muscleFile != null) {
				for (int i = 0; i < muscleFile.length; i++) {
					if (muscleFile[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = muscleFile[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		if (!isFound) {
			File hoofFile[] = Downloader.getFileList(Constants.HOOFS_DIRECTORY);
			if (hoofFile != null) {
				for (int i = 0; i < hoofFile.length; i++) {
					if (hoofFile[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = hoofFile[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		if (!isFound) {
			File deepFile[] = Downloader
					.getFileList(Constants.DEEP_MUSCLES_DIRECTORY);

			if (deepFile != null) {
				for (int i = 0; i < deepFile.length; i++) {
					if (deepFile[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = deepFile[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		if (!isFound) {
			File headFile[] = Downloader.getFileList(Constants.HEAD_DIRECTORY);

			if (headFile != null) {
				for (int i = 0; i < headFile.length; i++) {
					if (headFile[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = headFile[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		if (!isFound) {
			File organsFile[] = Downloader
					.getFileList(Constants.ORGANS_DIRECTORY);
			if (organsFile != null) {
				for (int i = 0; i < organsFile.length; i++) {
					if (organsFile[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = organsFile[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		return path;
	}

	private boolean isInRaw(String fileName) {
		try {
			int imageId = 0;
			imageId = getResources().getIdentifier(Utils.getFileName(fileName),
					"raw", getClass().getPackage().getName());
			if (imageId != 0) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	private void showQuizeAimation() {
		try {
			new AsyncTask<String, String, String>() {
				private JSONArray ja;
				private JSONObject jo;

				@Override
				protected void onPreExecute() {
					try {

						jo = new JSONObject(jsonString);
						ja = jo.getJSONObject("root").getJSONArray("horse");
						for (int k = 0; k < ja.length(); k++) {
							String fileName = ja.getJSONObject(k).getString(
									"-parent");
							Log.i("DREG",
									"fileName = " + Utils.getFileName(fileName));
						}

						nrr = new NoRepeatRandom(0, ja.length() - 1);
						targetPosition = new int[ja.length()];

						for (int i = 0; i < ja.length(); i++) {
							targetPosition[i] = nrr.GetRandom();
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				protected void onProgressUpdate(String... arg0) {
					try {

						if (isPinDrop) {
							ViewGroup vg = (ViewGroup) (pinView.getParent());
							vg.removeView(pinView);
							isPinDrop = false;
						}

						currentPosition++;
						quizeButton.setVisibility(View.VISIBLE);
						quizeButton
								.setBackgroundResource(R.drawable.quize_button);
						quizeButton.setTextColor(Color.WHITE);
						quizeButton.setEnabled(true);

						if (currentPosition < ja.length()) {

							Log.i("DREG", "Current Index=" + currentPosition);
							if (isTimer) {
								showTimer(remainingTime);
							}

							isCorrect = false;
							isClick = true;
							quesTextView.setText("Question "
									+ (currentPosition + 1));

							String fileName = ja.getJSONObject(
									targetPosition[currentPosition]).getString(
									"-parent");
							partFileName = ja.getJSONObject(
									targetPosition[currentPosition]).getString(
									"-part");
							if (isInRaw(Utils.getFileName(fileName))) {
								int imageId = getResources().getIdentifier(
										Utils.getFileName(fileName), "raw",
										getClass().getPackage().getName());

								// partImageId = getResources().getIdentifier(
								// Utils.getFileName(partFileName), "raw",
								// getClass().getPackage().getName());

								Bitmap bm = BitmapFactory.decodeResource(
										getResources(), imageId);
								Bitmap ret = Bitmap.createBitmap(
										imageViewWidth, imageViewHeight,
										Bitmap.Config.ARGB_8888);
								Canvas comboImage = new Canvas(ret);
								Rect r1 = new Rect(0, 0, bm.getWidth(),
										bm.getHeight());
								Rect r2 = new Rect(0, 0, imageViewWidth,
										imageViewHeight);
								comboImage.drawBitmap(bm, r1, r2, null);
								comboImage.save();
								imageView.setImageBitmap(ret);
							} else {
								Bitmap bm = BitmapFactory
										.decodeFile(getFilePath(fileName));
								Bitmap ret = Bitmap.createBitmap(
										imageViewWidth, imageViewHeight,
										Bitmap.Config.ARGB_8888);
								Canvas comboImage = new Canvas(ret);
								Rect r1 = new Rect(0, 0, bm.getWidth(),
										bm.getHeight());
								Rect r2 = new Rect(0, 0, imageViewWidth,
										imageViewHeight);
								comboImage.drawBitmap(bm, r1, r2, null);
								comboImage.save();
								imageView.setImageBitmap(ret);
							}

							// imageView.setImageResource(imageId);

							String partName = ja.getJSONObject(
									targetPosition[currentPosition]).getString(
									"-part");
							String name;
							if (partName.contains("vertebrae")) {
								name = partName.replace("vertebrae",
										"vertabrae");
								quizeButton.setText(name);
							} else {
								name = partName;
							}

							if (partName.contains("_(HOOFSIDE)")) {
								name = partName.replace("_(HOOFSIDE)", "");
							}
							
							if (partName.contains("_RECALL")) {
								name = partName.replace("_RECALL", "");
							}

							quizeButton.setText(name);
						} else {
							timerView.setVisibility(View.GONE);
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				protected String doInBackground(String... arg0) {
					try {

						while ((currentPosition < ja.length()) && (!isExit)) {
							if (isTimer) {
								Random random = new Random();
								randomValue = random.nextInt(4);
								if (!isPause) {
									publishProgress("");
								}
								Thread.sleep(Constants.WAITING_TIME);
							} else {
								if (isNextQuestion) {
									isNextQuestion = false;
									Random random = new Random();
									randomValue = random.nextInt(4);
									if (currentPosition != -1) {
										Thread.sleep(Constants.POST_CLICK_TIME);
									}
									publishProgress("");
									// Thread.sleep(Constants.PRE_CLICK_TIME);

								}
							}
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
					return null;
				}

				@Override
				protected void onPostExecute(String unused) {

					int percent = (int) ((score * 100) / (ja.length() * 10));
					quesTextView.setVisibility(View.GONE);
					imageView.setAlpha(0x55);
					timerView.setText("0.0");
					quizeButton.setVisibility(View.INVISIBLE);
					mainMenuButton.setVisibility(View.VISIBLE);
					tryButton.setVisibility(View.VISIBLE);
					facebookButton.setVisibility(View.VISIBLE);
					twitterButton.setVisibility(View.VISIBLE);
					alertView.setVisibility(View.VISIBLE);
					pauseView.setVisibility(View.INVISIBLE);

					mainMenuButton.setEnabled(true);
					tryButton.setEnabled(true);
					facebookButton.setEnabled(true);
					twitterButton.setEnabled(true);

					if (percent < 70) {
						isNextLevel = false;
						congratulationView.setText("Sorry ):");
						alertView.setText("You only scored " + score
								+ " points with " + percent + "% accuracy.");
					} else {
						isNextLevel = true;
						tryButton.setText("Next Level");
						congratulationView.setText("Congratulations !");
						alertView.setText("You have scored " + score
								+ " points with " + percent + "% accuracy.");
						int highestScore = Utils.getLevelHighestScore(
								RecallQuizeActivity.this,
								Constants.KEY_RECALL_SCORE + level);
						if (score > highestScore) {
							Utils.putLevelHighestScore(
									RecallQuizeActivity.this,
									Constants.KEY_RECALL_SCORE + level, score);
							Utils.putPrecentage(RecallQuizeActivity.this,
									Constants.KEY_RECALL_PERCENTAGE + level,
									percent);
						}

					}
				}
			}.execute();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	class ImplementQuiz extends AsyncTask<String, String, String> {
		private int currentIndex;
		private long waitingTime;

		public ImplementQuiz(int currentIndex, long waitingTime) {
			super();
			this.currentIndex = currentIndex;
			this.waitingTime = waitingTime;
		}

		protected void onProgressUpdate(String... arg0) {
			try {

				if (isPinDrop) {
					ViewGroup vg = (ViewGroup) (pinView.getParent());
					vg.removeView(pinView);
					isPinDrop = false;
				}
				pauseView.setEnabled(true);
				quizeIndex = currentIndex;
				currentIndex++;
				currentPosition = currentIndex;
				quizeButton.setVisibility(View.VISIBLE);
				quizeButton.setBackgroundResource(R.drawable.quize_button);
				quizeButton.setTextColor(Color.WHITE);
				quizeButton.setEnabled(true);

				if (currentIndex < ja.length()) {

					Log.i("DREG", "Current Index=" + currentIndex);
					if (isTimer) {
						showTimer(waitingTime);
					}

					isCorrect = false;
					isClick = true;
					quesTextView.setText("Question " + (currentIndex + 1));

					String fileName = ja.getJSONObject(
							targetPosition[currentIndex]).getString("-parent");
					partFileName = ja.getJSONObject(
							targetPosition[currentIndex]).getString("-part");
					if (isInRaw(Utils.getFileName(fileName))) {
						int imageId = getResources().getIdentifier(
								Utils.getFileName(fileName), "raw",
								getClass().getPackage().getName());

						Bitmap bm = BitmapFactory.decodeResource(
								getResources(), imageId);
						Bitmap ret = Bitmap.createBitmap(imageViewWidth,
								imageViewHeight, Bitmap.Config.ARGB_8888);
						Canvas comboImage = new Canvas(ret);
						Rect r1 = new Rect(0, 0, bm.getWidth(), bm.getHeight());
						Rect r2 = new Rect(0, 0, imageViewWidth,
								imageViewHeight);
						comboImage.drawBitmap(bm, r1, r2, null);
						comboImage.save();
						imageView.setImageBitmap(ret);
					} else {
						Bitmap bm = BitmapFactory
								.decodeFile(getFilePath(fileName));
						Bitmap ret = Bitmap.createBitmap(imageViewWidth,
								imageViewHeight, Bitmap.Config.ARGB_8888);
						Canvas comboImage = new Canvas(ret);
						Rect r1 = new Rect(0, 0, bm.getWidth(), bm.getHeight());
						Rect r2 = new Rect(0, 0, imageViewWidth,
								imageViewHeight);
						comboImage.drawBitmap(bm, r1, r2, null);
						comboImage.save();
						imageView.setImageBitmap(ret);
					}

					// imageView.setImageResource(imageId);

					String partName = ja.getJSONObject(
							targetPosition[currentIndex]).getString("-part");
					String name;
					if (partName.contains("vertebrae")) {
						name = partName.replace("vertebrae", "vertabrae");
						quizeButton.setText(name);
					} else {
						name = partName;
					}

					if (partName.contains("_(HOOFSIDE)")) {
						name = partName.replace("_(HOOFSIDE)", "");
					}

					quizeButton.setText(name);
					if (currentIndex < (ja.length() - 1)) {
						waitingTime = 10000;
					} else {
						waitingTime = 500;
					}

				} else {
					timerView.setVisibility(View.GONE);
					tView.setVisibility(View.INVISIBLE);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		protected String doInBackground(String... arg0) {
			try {

				while ((currentIndex < ja.length()) && (!isExit)) {
					if (isTimer) {
						Random random = new Random();
						randomValue = random.nextInt(4);
						if (!isPause) {
							publishProgress("");
						}
						Thread.sleep(waitingTime);
					} else {
						if (isNextQuestion) {
							isNextQuestion = false;
							Random random = new Random();
							randomValue = random.nextInt(4);
							if (currentIndex != -1) {
								Thread.sleep(Constants.POST_CLICK_TIME);
							}
							publishProgress("");
							Thread.sleep(Constants.PRE_CLICK_TIME);

						}
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String unused) {

			int percent = (int) ((correctAnswer * 100) / (ja.length()));
			quesTextView.setVisibility(View.GONE);
			imageView.setAlpha(0x55);
			timerView.setText("0.0");
			quizeButton.setVisibility(View.INVISIBLE);
			mainMenuButton.setVisibility(View.VISIBLE);
			tryButton.setVisibility(View.VISIBLE);
			facebookButton.setVisibility(View.VISIBLE);
			twitterButton.setVisibility(View.VISIBLE);
			alertView.setVisibility(View.VISIBLE);
			pauseView.setVisibility(View.INVISIBLE);

			mainMenuButton.setEnabled(true);
			tryButton.setEnabled(true);
			facebookButton.setEnabled(true);
			twitterButton.setEnabled(true);

			if (percent < 70) {
				isNextLevel = false;
				congratulationView.setText("Sorry :)");
				alertView.setText("You only scored " + score + " points with "
						+ percent + "% accuracy.");
			} else {
				isNextLevel = true;
				tryButton.setText("Next Level");
				congratulationView.setText("Congratulations !");
				alertView.setText("You have scored " + score + " points with "
						+ percent + "% accuracy.");
				int highestScore = Utils.getLevelHighestScore(
						RecallQuizeActivity.this, Constants.KEY_RECALL_SCORE
								+ level);
				if (score > highestScore) {
					Utils.putLevelHighestScore(RecallQuizeActivity.this,
							Constants.KEY_RECALL_SCORE + level, score);
					Utils.putPrecentage(RecallQuizeActivity.this,
							Constants.KEY_RECALL_PERCENTAGE + level, percent);
				}

			}
		}
	}

	private int posX = 0;
	private int posY = 0;

	private boolean isCorrect;

	private void implementQuiz() {
		pauseView.setEnabled(false);
		Bitmap bm = null;
		if (isInRaw(partFileName)) {
			int imgId = getResources().getIdentifier(
					Utils.getFileName(partFileName), "raw",
					getClass().getPackage().getName());
			bm = BitmapFactory.decodeResource(getResources(), imgId);
		} else {
			bm = BitmapFactory.decodeFile(getFilePath(partFileName));
		}
		Bitmap ret = Bitmap.createBitmap(imageViewWidth, imageViewHeight,
				Bitmap.Config.ARGB_8888);
		Canvas comboImage = new Canvas(ret);
		Rect r1 = new Rect(0, 0, bm.getWidth(), bm.getHeight());
		Rect r2 = new Rect(0, 0, imageViewWidth, imageViewHeight);
		comboImage.drawBitmap(bm, r1, r2, null);
		comboImage.save();
		JSONArray points = items.get(targetPosition[currentPosition]);

		for (int i = 0; i < points.length(); i++) {
			try {
				int x1 = (int) (points.getJSONObject(i).getInt("-x1") * factor);
				int x2 = (int) (points.getJSONObject(i).getInt("-x2") * factor);
				int y1 = (int) (points.getJSONObject(i).getInt("-y1") * factor);
				int y2 = (int) (points.getJSONObject(i).getInt("-y2") * factor);
				// comboImage.drawRect(new Rect(x1,y1,x2,y2 ),paint);
				if ((posX >= x1 && posX <= x2) && (posY >= y1 && posY <= y2)) {
					isCorrect = true;
					break;
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (isCorrect) {
			score += 10 + bonusScore;
			++correctAnswer;
			scoreView.setText("" + score);
			if (isTimer) {
				quesTextView.setText(bonusScore + " Bonus points");
			}

			// imageView.setImageResource(partImageId);
			imageView.setImageBitmap(ret);
			quizeButton.setBackgroundResource(R.drawable.quiz_answer_correct);
			Utils.play(RecallQuizeActivity.this, R.raw.sound_correct);
		} else {
			score += 0;
			scoreView.setText("" + score);
			// imageView.setImageResource(partImageId);
			imageView.setImageBitmap(ret);
			quizeButton.setBackgroundResource(R.drawable.quiz_answer_wrong);
			Utils.play(RecallQuizeActivity.this, R.raw.sound_incorrect);
			Utils.vibratePhone(RecallQuizeActivity.this);
		}
		isNextQuestion = true;
		isClick = false;
		if (!isPinDrop) {
			dropPin();
		}

		if (isTimer) {
			try {
				new AsyncTask<String, String, String>() {
					@Override
					protected void onPreExecute() {
						try {
							iquize.cancel(true);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					@Override
					protected String doInBackground(String... arg0) {
						try {
							Log.i("DREG", "Quize index =" + quizeIndex);
							if (quizeIndex < (numOfQuestion - 2)) {
								Thread.sleep(Constants.WAITING_FOR_NEXT);
							} else {
								Thread.sleep(500);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						return null;
					}

					@Override
					protected void onPostExecute(String unused) {

						// dropPin();
						if (quizeIndex < (numOfQuestion - 2)) {
							iquize = new ImplementQuiz(++quizeIndex,
									Constants.WAITING_TIME);
						} else {
							iquize = new ImplementQuiz(++quizeIndex, 0);
						}
						iquize.execute();
					}
				}.execute();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void animatePin(ImageView imageView, Bitmap bitmap, int animTime)
			throws Exception {

		imageView.setVisibility(View.VISIBLE);
		final TranslateAnimation anim = new TranslateAnimation(posX
				- bitmap.getWidth() / 2, posX - bitmap.getWidth() / 2,
				-bitmap.getHeight(), posY - bitmap.getHeight());

		/* new TranslateAnimation(fromXDelta, toXDelta, fromYDelta, toYDelta) */

		anim.setDuration(animTime);
		anim.setFillAfter(true);
		anim.setAnimationListener(new Animation.AnimationListener() {
			@Override
			public void onAnimationStart(Animation arg0) {
			}

			@Override
			public void onAnimationRepeat(Animation arg0) {
			}

			@Override
			public void onAnimationEnd(Animation arg0) {
			}
		});
		imageView.startAnimation(anim);
		imageView.setImageBitmap(bitmap);

	}

	private void dropPin() {

		pinView = new ImageView(this);
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
				bitmap.getWidth(), bitmap.getHeight());
		pinView.setLayoutParams(layoutParams);
		recallLayout.addView(pinView);
		if (isFirstTime) {
			pinView.setVisibility(View.GONE);
			isFirstTime = false;
		} else {
			pinView.setVisibility(View.INVISIBLE);
			try {
				animatePin(pinView, bitmap, Constants.PIN_ANIMTED_TIME);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		isPinDrop = true;
	}

	private void getPointsList() {
		try {
			// jo = new JSONObject(jsonString);
			ja = jo.getJSONObject("root").getJSONArray("horse");
			for (int i = 0; i < ja.length(); i++) {
				JSONArray points = ja.getJSONObject(i).getJSONArray("points");
				items.add(points);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
